package com.ins1st.config;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.ins1st.core.Page;
import com.ins1st.model.GenEntity;
import com.ins1st.util.ColumnUtil;
import com.ins1st.util.FileUtil;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成
 *
 * @author sun
 */
@Component
public class GenConfig {

    private static final Logger log = LoggerFactory.getLogger(GenConfig.class);

    private static final String TEMPLATE_PATH = System.getProperty("user.dir") + "/ins1st-generator/src/main/resources/templates";

    public void start(GenEntity genEntity) {
        List<TableInfo> infoList = genMp(genEntity);
        GroupTemplate groupTemplate = initBeetlGroupTemplate();
        if (genEntity.isGenIndexJs() || genEntity.isGenAddHtml() || genEntity.isGenAddHtml() || genEntity.isGenAddJs() || genEntity.isGenEditHtml() || genEntity.isGenEditJs()) {
            createFront(genEntity.getModuleName(), genEntity.getBizName());
        }
        if (genEntity.isGenIndexHtml()) {
            createIndexHtml(groupTemplate, genEntity, getMap(genEntity, infoList));
        }
        if (genEntity.isGenIndexJs()) {
            createIndexJs(groupTemplate, genEntity, getMap(genEntity, infoList));
        }
        if (genEntity.isGenAddHtml()) {
            createAddHtml(groupTemplate, genEntity, getMap(genEntity, infoList));
        }
        if (genEntity.isGenAddJs()) {
            createAddJs(groupTemplate, genEntity, getMap(genEntity, infoList));
        }
        if (genEntity.isGenEditHtml()) {
            createEditHtml(groupTemplate, genEntity, getMap(genEntity, infoList));
        }
        if (genEntity.isGenEditJs()) {
            createEditJs(groupTemplate, genEntity, getMap(genEntity, infoList));
        }

    }

    private List<TableInfo> genMp(GenEntity genEntity) {
        AutoGenerator mpg = new AutoGenerator();
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(System.getProperty("user.dir") + "/ins1st-web/src/main/java/");
        gc.setAuthor(genEntity.getAuthor());
        gc.setFileOverride(true);
        gc.setOpen(false);
        if (!genEntity.isGenController()) {
            gc.setControllerName("TTTController");
        }
        if (!genEntity.isGenService()) {
            gc.setServiceName("TTTService");
        }
        if (!genEntity.isGenServiceImpl()) {
            gc.setServiceImplName("TTTServiceImpl");
        }
        if (!genEntity.isGenEntity()) {
            gc.setEntityName("TTTEntity");
        }
        if (!genEntity.isGenDao()) {
            gc.setMapperName("TTTMapper");
        }
        if (!genEntity.isGenXml()) {
            gc.setXmlName("TTTXml");
        }
        mpg.setGlobalConfig(gc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("moduleName", genEntity.getModuleName());
                map.put("bizName", genEntity.getBizName());
                map.put("service", "I" + ColumnUtil.underline2Camel(genEntity.getTableName(), false) + "Service");
                map.put("service2", ColumnUtil.underline2Camel(genEntity.getTableName(), true) + "Service");
                map.put("serviceImpl", ColumnUtil.underline2Camel(genEntity.getTableName(), true) + "ServiceImpl");
                map.put("entity", ColumnUtil.underline2Camel(genEntity.getTableName(), false));
                map.put("entityS", ColumnUtil.underline2Camel(genEntity.getTableName(), true));
                setMap(map);
            }
        };
        mpg.setCfg(cfg);
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(genEntity.getUrl());
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername(genEntity.getUsername());
        dsc.setPassword(genEntity.getPassword());
        mpg.setDataSource(dsc);
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(genEntity.getModuleName());
        pc.setParent("com.ins1st.modules");
        mpg.setPackageInfo(pc);
        TemplateConfig templateConfig = new TemplateConfig();
        mpg.setTemplate(templateConfig);
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setInclude(genEntity.getTableName());
        strategy.setSuperEntityClass(Page.class);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        log.info("modulesName:{},tableName:{},author:{},生成代码初始化完成......", genEntity.getModuleName(), genEntity.getTableName(), genEntity.getAuthor());
        mpg.execute();
        FileUtil.deleteTTT(System.getProperty("user.dir") + "/ins1st-web/src/main/java/");
        ConfigBuilder configBuilder = new ConfigBuilder(pc, dsc, strategy, mpg.getTemplate(), gc);
        List<TableInfo> infoList = configBuilder.getTableInfoList();
        log.debug("获取" + genEntity.getTableName() + "表成功......");
        return infoList;
    }


    /**
     * 初始化beetl
     *
     * @return
     */
    private GroupTemplate initBeetlGroupTemplate() {
        FileResourceLoader resourceLoader = new FileResourceLoader(TEMPLATE_PATH, "utf-8");
        Configuration cfg = null;
        GroupTemplate gt = null;
        try {
            cfg = Configuration.defaultConfiguration();
            gt = new GroupTemplate(resourceLoader, cfg);
        } catch (IOException e) {
            log.debug("模板未找到......");
            System.out.println();
        }

        return gt;
    }

    /**
     * 创建前端文件夹
     *
     * @param moduleName
     * @param bizName
     */
    private void createFront(String moduleName, String bizName) {
        FileUtil.createDir(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/templates/modules/" + moduleName + "/" + bizName);
        FileUtil.createDir(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/static/modules/" + moduleName + "/" + bizName);
    }

    private Map<String, Object> getMap(GenEntity genEntity, List<TableInfo> getTableInfo) {
        genEntity.setInfoList(getTableInfo);
        Map<String, Object> map = new HashMap<>();
        map.put("ge", genEntity);
        map.put("columns", genEntity.getInfoList().get(0).getFields());
        map.put("tableComment", genEntity.getInfoList().get(0).getComment());
        return map;
    }

    /**
     * 创建indexhtml
     *
     * @param groupTemplate
     * @param genEntity
     * @param map
     */
    private void createIndexHtml(GroupTemplate groupTemplate, GenEntity genEntity, Map<String, Object> map) {
        Writer out = null;
        try {
            FileUtil.createFile(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/templates/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_index.html");
            out = new FileWriter(new File(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/templates/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_index.html"));
            GroupTemplate gt = initBeetlGroupTemplate();
            Template t = gt.getTemplate("/index.txt");
            t.binding("map", map);
            t.renderTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建indexjs
     *
     * @param groupTemplate
     * @param genEntity
     * @param map
     */
    private void createIndexJs(GroupTemplate groupTemplate, GenEntity genEntity, Map<String, Object> map) {
        Writer out = null;
        try {
            FileUtil.createFile(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/static/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_index.js");
            out = new FileWriter(new File(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/static/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_index.js"));
            GroupTemplate gt = initBeetlGroupTemplate();
            Template t = gt.getTemplate("/index.js.txt");
            t.binding("map", map);
            t.renderTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建addhtml
     *
     * @param groupTemplate
     * @param genEntity
     * @param map
     */
    private void createAddHtml(GroupTemplate groupTemplate, GenEntity genEntity, Map<String, Object> map) {
        Writer out = null;
        try {
            FileUtil.createFile(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/templates/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_add.html");
            out = new FileWriter(new File(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/templates/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_add.html"));
            GroupTemplate gt = initBeetlGroupTemplate();
            Template t = gt.getTemplate("/add.txt");
            t.binding("map", map);
            t.renderTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建addJs
     *
     * @param groupTemplate
     * @param genEntity
     * @param map
     */
    private void createAddJs(GroupTemplate groupTemplate, GenEntity genEntity, Map<String, Object> map) {
        Writer out = null;
        try {
            FileUtil.createFile(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/static/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_add.js");
            out = new FileWriter(new File(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/static/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_add.js"));
            GroupTemplate gt = initBeetlGroupTemplate();
            Template t = gt.getTemplate("/add.js.txt");
            t.binding("map", map);
            t.renderTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建edithtml
     *
     * @param groupTemplate
     * @param genEntity
     * @param map
     */
    private void createEditHtml(GroupTemplate groupTemplate, GenEntity genEntity, Map<String, Object> map) {
        Writer out = null;
        try {
            FileUtil.createFile(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/templates/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_edit.html");
            out = new FileWriter(new File(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/templates/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_edit.html"));
            GroupTemplate gt = initBeetlGroupTemplate();
            Template t = gt.getTemplate("/edit.txt");
            t.binding("map", map);
            t.renderTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建editJs
     *
     * @param groupTemplate
     * @param genEntity
     * @param map
     */
    private void createEditJs(GroupTemplate groupTemplate, GenEntity genEntity, Map<String, Object> map) {
        Writer out = null;
        try {
            FileUtil.createFile(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/static/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_edit.js");
            out = new FileWriter(new File(System.getProperty("user.dir") + "/ins1st-web/src/main/resources/static/modules/" + genEntity.getModuleName() + "/" + genEntity.getBizName() + "/" + genEntity.getBizName() + "_edit.js"));
            GroupTemplate gt = initBeetlGroupTemplate();
            Template t = gt.getTemplate("/edit.js.txt");
            t.binding("map", map);
            t.renderTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
